package me.healthcare.webserivce;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.AsyncTask;

public class GraphService extends AsyncTask<Void, Void, Void> {

	private long patient_id;
	private ArrayList<Double> records;
	private String executeURL;
	private final String SUGAR_URL = "/sworldwebservice/sworld/app/GetSugarListByPatients_id/12345";
	private final String PRESSURE_URL = "/sworldwebservice/sworld/app/GetSugarListByPatients_id/12345";

	@Override
	protected Void doInBackground(Void... params) {
		URL jsonURL;
		URLConnection jc;
		try {
			jsonURL = new URL("http://" + WebService.HOST_IP + executeURL + "/"
					+ patient_id);

			jc = jsonURL.openConnection();
			InputStream is = jc.getInputStream();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			String jsonTxt = sb.toString();
			JSONObject jj = new JSONObject(jsonTxt);

			JSONArray obj = jj.getJSONArray("obj");

			records = new ArrayList<Double>();
			for (int i = 0; i < obj.length(); i++) {
				JSONObject duongHuyet = obj.getJSONObject(i);
				double a = (duongHuyet.getDouble("giaTri"));
				records.add(a);
			}
		} catch (Exception e) {
		}
		return null;
	}

	public ArrayList<Double> getSugarRecords(long patient_id) {
		this.patient_id = patient_id;
		executeURL = SUGAR_URL;
		this.execute();
		return records;
	}

	public ArrayList<Double> getPressureRecords(long patient_id) {
		this.patient_id = patient_id;
		executeURL = PRESSURE_URL;
		this.execute();
		return records;
	}

}
